<!--
  @author:  long
  @date:    2023/8/10
  @file:    xx
  @require:
-->
<template>
  <div class="accountStatistics app-container">
    <!--   头部   -->
    <el-row :gutter="20" class="account-box">
      <el-col :span="6" v-for="(item, index) in accountBoxData" :key="index">
        <el-card class="box-card">
          <div class="mb-1 text-lg text-slate-800">{{ item.label }}</div>
          <div class="text-4xl font-semibold">
            {{ headerData[item.prop] != null ? headerData[item.prop] : 0 }}
          </div>
          <div class="box-icon">
            <img :src="getIcon(item.icon)" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-card class="mb-5">
      <!--   查询   -->
      <el-row class="mb-5">
        <el-col :span="16" class="flex">
          <el-radio-group v-model="timeType" class="mr-5" @change="handleQuery">
            <el-radio-button label="month">月</el-radio-button>
            <el-radio-button label="week">周</el-radio-button>
            <el-radio-button label="day">日</el-radio-button>
            <el-radio-button label="year">年</el-radio-button>
          </el-radio-group>

          <div class="mr-5">
            <template v-if="timeType == 'month'">
              <el-date-picker
                v-model="monthValue"
                type="monthrange"
                :clearable="false"
                placeholder="选择月份"
                value-format="YYYY-MM"
              />
            </template>
            <template v-if="timeType == 'week'">
              <el-date-picker
                v-model="weekValue"
                :clearable="false"
                placeholder="选择周"
                type="week"
                format="YYYY[ 第] w [周]"
                @change="weekChange"
              />
            </template>
            <template v-if="timeType == 'day'">
              <el-date-picker
                v-model="dayValue"
                type="daterange"
                :clearable="false"
                placeholder="选择日期范围"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </template>
            <template v-if="timeType == 'year'">
              <el-date-picker
                v-model="yearValue"
                type="year"
                :clearable="false"
                placeholder="选择年份"
                format="YYYY"
                value-format="YYYY"
              />
            </template>
          </div>
          <el-tree-select
            v-if="userStore.user.orgId == 484"
            v-model="orgId"
            :data="companyOptions"
            :props="{
              value: 'id',
              label: 'label',
              children: 'children'
            }"
            placeholder="请选择公司"
            value-key="id"
            filterable
            clearable
            @current-change="handleGetBizstatisticsEcahrtData"
          />
        </el-col>
        <el-col :span="8" class="text-right">
          <el-button type="primary" icon="Search" @click="handleQuery"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="handleRefresh">重置</el-button>
          <el-button icon="Upload" @click="handleOutput">导出</el-button>
        </el-col>
      </el-row>

      <!--    表格    -->
      <div class="mb-5">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="orgName" label="单位" align="center" />
          <el-table-column label="时间" align="center">
            <template #default="scope">
              {{ scope.row.times }}
              <!--              <div v-if="timeType == 'month'">-->
              <!--                {{ scope.row.year }}年{{ scope.row.month }}月-->
              <!--              </div>-->
              <!--              <div v-if="timeType == 'week'">-->
              <!--                {{ scope.row.year }}年{{ scope.row.week }}周-->
              <!--              </div>-->
              <!--              <div v-if="timeType == 'day'">-->
              <!--                {{ scope.row.createTime }}-->
              <!--              </div>-->
              <!--              <div v-if="timeType == 'year'">-->
              <!--                {{ scope.row.year }}-->
              <!--              </div>-->
            </template>
          </el-table-column>
          <el-table-column prop="ljdzjg" label="累计代账机构" align="center" />
          <el-table-column
            prop="ljjgkhs"
            label="累计机构客户数"
            align="center"
          />
          <el-table-column prop="qwdzjg" label="签约代账机构" align="center" />
          <el-table-column prop="sdpzs" label="数电配置数" align="center" />
          <el-table-column prop="xzdzjg" label="新增代账机构" align="center" />
          <el-table-column
            prop="xzjgkhs"
            label="新增机构客户数"
            align="center"
          />
        </el-table>
        <pagination
          v-show="total > 12"
          :total="total"
          v-model:page="queryForm.pageNum"
          v-model:limit="queryForm.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>
    <el-card>
      <div ref="myChart" style="height: 350px"></div>
    </el-card>
  </div>
</template>

<script setup name="AccountStatistics">
import { getCurrentInstance, ref } from 'vue'
import useUserStore from '@/store/modules/user'
import useCommonStore from '@/store/modules/common'
import * as echarts from 'echarts'

const userStore = useUserStore()
// 通用数据store
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
import {
  startOfWeek,
  endOfWeek,
  format,
  addDays,
  startOfMonth,
  endOfMonth
} from 'date-fns'
import {
  getBizstatisticsEcahrtData,
  getBizstatisticsList,
  getBizstatisticsMonthMsg
} from '@/api/statistical/accountStatistics'

const data = reactive({
  accountBoxData: [
    {
      label: '新增签约代账机构（月）',
      prop: 'xzdzjg',
      value: 120000,
      icon: 'institution'
    },
    {
      label: '新增签约机构客户（月）',
      prop: 'qwdzjg',
      value: 100000,
      icon: 'customer'
    },
    {
      label: '累计数电配置',
      prop: 'sdpzs',
      value: 1000,
      icon: 'digital'
    },
    {
      label: '累计代账客户数（服务期内）',
      prop: 'ljdzkhs',
      value: 100000,
      icon: 'accumulate'
    }
  ],
  headerData: {
    xzdzjg: 0,
    xzjgkhs: 0,
    sdpzs: 0,
    ljdzjg: 0
  },
  timeType: 'month', //时间类型单选框
  weekValue: format(new Date(), 'yyyy-MM-dd'), //周选择框
  monthValue: [
    format(startOfMonth(new Date()), 'yyyy-MM-dd'),
    format(endOfMonth(new Date()), 'yyyy-MM-dd')
  ], //月选择框
  dayValue: [
    format(new Date(), 'yyyy-MM-dd'),
    format(new Date(), 'yyyy-MM-dd')
  ], //日选择框
  yearValue: format(new Date(), 'yyyy'), //年选择框
  companyOptions: [],
  orgId: userStore.user.orgId, //公司id
  tableData: [],
  queryForm: {
    pageNum: 1,
    pageSize: 10
  },
  total: 0,
  firstDayOfWeek: format(
    addDays(startOfWeek(new Date(), { weekStartsOn: 6 }), 2),
    'yyyy-MM-dd'
  ),
  lastDayOfWeek: format(
    addDays(endOfWeek(new Date(), { weekStartsOn: 6 }), 2),
    'yyyy-MM-dd'
  )
})
const {
  accountBoxData,
  timeType,
  weekValue,
  monthValue,
  dayValue,
  yearValue,
  companyOptions,
  orgId,
  tableData,
  queryForm,
  total,
  headerData,
  firstDayOfWeek,
  lastDayOfWeek
} = toRefs(data)
const myChart = ref(null)
const imgBase = ref('../../../assets/images/icon/')

/**
 * 导出
 * @param val
 */
const handleOutput = () => {
  let params = {
    orgId: orgId.value,
    ...queryForm.value
  }
  switch (timeType.value) {
    case 'month':
      params.type = '2'
      console.info('1', monthValue.value)
      params.startTime = format(
        startOfMonth(new Date(monthValue.value[0])),
        'yyyy-MM-dd'
      )
      params.endTime = format(
        endOfMonth(new Date(monthValue.value[1])),
        'yyyy-MM-dd'
      )
      break
    case 'week':
      params.type = '3'
      params.startTime = firstDayOfWeek.value
      params.endTime = lastDayOfWeek.value
      break
    case 'day':
      params.type = '4'
      params.startTime = dayValue.value[0]
      params.endTime = dayValue.value[1]
      break
    case 'year':
      params.type = '1'
      params.startTime = yearValue.value + '-01-01'
      params.endTime = yearValue.value + '-12-31'
      break
  }
  proxy.downLoadByUrl(
    '/customer/bizstatistics/outPutExcel',
    params,
    '代账统计信息.xlsx'
  )
}
// 周时间处理
const weekChange = val => {
  console.info(val)
  const startOfWeekDate = format(
    addDays(startOfWeek(val, { weekStartsOn: 6 }), 2),
    'yyyy-MM-dd'
  )
  const endOfWeekDate = format(
    addDays(endOfWeek(val, { weekStartsOn: 6 }), 2),
    'yyyy-MM-dd'
  )
  firstDayOfWeek.value = startOfWeekDate
  lastDayOfWeek.value = endOfWeekDate
  console.info(startOfWeekDate, endOfWeekDate)
}

const getIcon = name => {
  return new URL(`../../../assets/images/icon/${name}.png`, import.meta.url)
    .href
}
/**
 * 查询方法
 */
const handleQuery = () => {
  queryForm.value.pageNum = 1
  getList()
}

/**
 * 重置方法
 */
const handleRefresh = () => {
  queryForm.value.pageNum = 1
  orgId.value = userStore.user.orgId
  switch (timeType.value) {
    case 'month':
      monthValue.value = [
        format(startOfMonth(new Date()), 'yyyy-MM-dd'),
        format(endOfMonth(new Date()), 'yyyy-MM-dd')
      ]
      break
    case 'week':
      weekValue.value = format(new Date(), 'yyyy-MM-dd')
      ;(firstDayOfWeek.value = format(
        addDays(startOfWeek(new Date(), { weekStartsOn: 6 }), 2),
        'yyyy-MM-dd'
      )),
        (lastDayOfWeek.value = format(
          addDays(endOfWeek(new Date(), { weekStartsOn: 6 }), 2),
          'yyyy-MM-dd'
        ))
      break
    case 'day':
      dayValue.value = [
        format(new Date(), 'yyyy-MM-dd'),
        format(new Date(), 'yyyy-MM-dd')
      ]

      break
    case 'year':
      yearValue.value = format(new Date(), 'yyyy') //年选择框
      break
  }
  getList()
}

/**
 * chat图表数据获取
 */
const handleGetBizstatisticsEcahrtData = node => {
  let params = {
    orgId: node.id == 484 ? '' : node.id,
    startTime: format(new Date(), 'yyyy-MM-dd')
  }
  getBizstatisticsEcahrtData(params).then(res => {
    let xData = res.data.map(item => {
      return item.year + '-' + item.month
    })
    let dzjgData = res.data.map(item => {
      return item.xzdzjg
    })
    let dzkhData = res.data.map(item => {
      return item.xzjgkhs
    })
    const myChartIntance = echarts.init(myChart.value, 'macarons')
    myChartIntance.setOption({
      title: {},
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['新签约代账机构数', '新签约代账客户数']
      },
      calculable: true,
      xAxis: [
        {
          type: 'category',
          // prettier-ignore
          data: xData
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '新签约代账机构数',
          type: 'bar',
          data: dzjgData
        },
        {
          name: '新签约代账客户数',
          type: 'bar',
          data: dzkhData
        }
      ]
    })
  })
}

/**
 * 获取列表
 */
const getList = () => {
  let params = {
    orgId: orgId.value,
    ...queryForm.value
  }
  switch (timeType.value) {
    case 'month':
      params.type = '2'
      console.info('1', monthValue.value)
      params.startTime = format(
        startOfMonth(new Date(monthValue.value[0])),
        'yyyy-MM-dd'
      )
      params.endTime = format(
        endOfMonth(new Date(monthValue.value[1])),
        'yyyy-MM-dd'
      )
      break
    case 'week':
      params.type = '3'
      params.startTime = firstDayOfWeek.value
      params.endTime = lastDayOfWeek.value
      break
    case 'day':
      params.type = '4'
      params.startTime = dayValue.value[0]
      params.endTime = dayValue.value[1]
      break
    case 'year':
      params.type = '1'
      params.startTime = yearValue.value + '-01-01'
      params.endTime = yearValue.value + '-12-31'
      break
  }
  getBizstatisticsList(params).then(res => {
    tableData.value = res.data.records
    total.value = res.data.total
  })
}

/**
 * 获取头部当月统计数据
 */
const getHeaderData = () => {
  let orgId = userStore.user.orgId
  getBizstatisticsMonthMsg(orgId).then(res => {
    console.info('res', res)
    if (res.data != null) {
      headerData.value = res.data
    }
  })
}
/**
 * 初始化
 */
function init() {
  //   获取所属公司数据
  commonStore.getCompanyData().then(data => {
    companyOptions.value = data
  })

  //   获取头部当月统计数据
  getHeaderData()
  // 代账统计列表
  getList()
  proxy.$nextTick(() => {
    let node = {
      id: userStore.user.orgId
    }
    //图表数据获取
    handleGetBizstatisticsEcahrtData(node)
  })
}

init()
</script>

<style scoped lang="scss">
.accountStatistics {
  .account-box {
    @apply mb-5;
  }
  .account-box {
    .box-card {
      @apply relative;
    }
    .box-icon {
      @apply absolute top-5 right-5;
      img {
        @apply w-18;
      }
    }
  }
}
</style>
